<template>
	<view class="page-container">
		<!-- 页面标题 -->
		<view class="page-header">
			<view class="header-content">
				<view class="header-icon">🍽️</view>
				<view class="header-text">
					<text class="header-title">选择套餐</text>
					<text class="header-subtitle" v-if="data.schoolId">
						学校ID: {{data.schoolId}} | 学生ID: {{data.studentId}}
					</text>
					<text class="header-subtitle" v-else>
						为学生选择本周用餐
					</text>
				</view>
			</view>
			<view class="weekend-notice" v-if="getLasetSaturday()">
				<up-icon name="info-circle" color="#FF9800" size="16"></up-icon>
				<text>周末不可选择套餐</text>
			</view>
		</view>

		<!-- 学生信息卡片 -->
		<view class="student-info-container" v-if="data.schoolId">
			<view class="student-info-card">
				<view class="info-header">
					<up-icon name="account" color="#6FD719" size="18"></up-icon>
					<text class="info-title">学生信息</text>
				</view>
				<view class="info-content">
					<view class="info-item">
						<text class="info-label">学生ID:</text>
						<text class="info-value">{{data.studentId}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">学校ID:</text>
						<text class="info-value">{{data.schoolId}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 套餐列表 -->
		<view class="content-container">
			<template v-if="data.comboList.length > 0">
				<view class="combo-day-section" v-for="(itemData,key) in data.comboList" :key="key">
					<view class="day-header">
						<view class="day-info">
							<text class="day-date">{{itemData.date}}</text>
							<text class="day-week">{{itemData.week}}</text>
						</view>
						<view class="selection-status" v-if="data.selectList[itemData.date]">
							<up-icon name="checkmark-circle" color="#6FD719" size="16"></up-icon>
							<text class="status-text">已选择</text>
						</view>
					</view>

					<view class="combo-list">
						<view
							class="combo-item-wrapper"
							v-for="(item, index) in itemData.comboList"
							:key="index"
							:class="{ 'combo-item-selected': data.selectList[itemData.date] === item.id }"
							@click="handleSelect(itemData.date, item.id)"
						>
							<ComboItem :item="item"></ComboItem>
							<view class="select-indicator">
								<view
									class="select-btn"
									:class="{ 'select-btn-active': data.selectList[itemData.date] === item.id }"
								>
									<up-icon
										v-if="data.selectList[itemData.date] === item.id"
										name="checkmark"
										color="#fff"
										size="16"
									></up-icon>
									<text v-else class="select-text">选择</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</template>

			<template v-else>
				<view class="empty-container">
					<up-empty
						mode="list"
						text="暂无可选套餐"
						textColor="#999"
						iconColor="#ddd"
					></up-empty>
				</view>
			</template>
		</view>

		<!-- 底部确认按钮 -->
		<view class="bottom-action">
			<view class="action-info">
				<text class="selected-count">已选择 {{getSelectedCount()}} / {{data.comboList.length}} 天</text>
			</view>
			<up-button
				type="primary"
				size="large"
				:disabled="getLasetSaturday() || !isAllSelected()"
				@click="handlerAddReserve"
				customStyle="background: linear-gradient(135deg, #6FD719 0%, #5BC016 100%); border: none; border-radius: 25rpx; box-shadow: 0 4px 16px rgba(111, 215, 25, 0.3);"
			>
				<up-icon name="checkmark" color="#fff" size="16" style="margin-right: 8rpx;"></up-icon>
				<text style="color: #fff; font-weight: 600;">确认选择</text>
			</up-button>
		</view>
	</view>
</template>

<script setup>
	import {
		reactive
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import ComboItem from '../../components/ComboItem/index.vue'
	import {
		getSelectComboList,getSelectComboByStudent,createResrve,getResrve
	} from '../../api/combo.js'
	const data = reactive({
		comboList: [],
		selectList: {},
		studentId: null,
		schoolId: null,
		studentInfo: null
	});


	onLoad(async (options) => {
		data.studentId = options.id;

		// 显示加载提示
		uni.showLoading({
			title: '加载中...',
			mask: true
		});

		try {
			// 根据学生ID获取套餐列表（后端会自动获取学生所在学校的菜单）
			console.log(`正在为学生ID ${data.studentId} 获取套餐列表...`);
			const result = await getSelectComboByStudent(data.studentId);
			console.log('后端返回的数据:', result);

			// 处理后端返回的数据结构
			if (result && typeof result === 'object') {
				if (result.comboList) {
					// 新的数据结构：包含学生信息、学校ID和套餐列表
					data.comboList = result.comboList;
					data.schoolId = result.schoolId;
					data.studentInfo = {
						studentId: result.studentId,
						schoolId: result.schoolId
					};

					console.log(`✅ 成功获取数据 - 学生ID: ${data.studentId}, 学校ID: ${data.schoolId}, 套餐数量: ${data.comboList.length}`);

					// 显示成功提示
					uni.showToast({
						title: `已加载学校${data.schoolId}的菜单`,
						icon: 'success',
						duration: 2000
					});
				} else if (Array.isArray(result)) {
					// 兼容旧的数据结构：直接返回数组
					data.comboList = result;
					console.log('⚠️ 使用兼容模式 - 套餐数量:', data.comboList.length);
				} else {
					data.comboList = [];
					console.log('⚠️ 未知的数据结构:', result);
				}
			} else if (Array.isArray(result)) {
				// 兼容旧的数据结构：直接返回数组
				data.comboList = result;
				console.log('⚠️ 直接数组格式 - 套餐数量:', data.comboList.length);
			} else {
				data.comboList = [];
				console.log('❌ 无效的数据格式:', result);
			}

			// 初始化选择列表
			if (data.comboList && data.comboList.length > 0) {
				data.comboList.forEach(combo => {
					data.selectList[combo.date] = null;
				});

				// 获取学生已有的预约记录
				const dateList = data.comboList.map(item => item.date);
				const resp = await getResrve({studentId: data.studentId, dateList: dateList});
				if (resp) {
					resp.forEach(item => {
						data.selectList[item.date] = item.dateComboId;
					});
				}
			}

		} catch (error) {
			console.error('加载套餐数据失败:', error);
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'none',
				duration: 3000
			});
		} finally {
			uni.hideLoading();
		}
	})
	const getLasetSaturday = () => {
		    const today = new Date();
		// 获取今天的星期几
		const todayDayOfWeek = today.getDay(); // 0 表示周日，6 表示周六
	
		if(todayDayOfWeek === 6 || todayDayOfWeek === 0){
			return true;
		}
		return  false;
	}
	

	const handlerAddReserve = async () => {
		const selectIds = [];
		for (var i = 0; i < data.comboList.length; i++) {
			if (data.selectList[data.comboList[i].date] === null) {
				uni.showModal({
					content: `${data.comboList[i].date}的套餐未选择，请先选择套餐`,
					title: '套餐选择'
				})
				return;
			}
			selectIds.push(data.selectList[data.comboList[i].date])
		}
		
		createResrve({studentId: data.studentId,comboIdList: selectIds}).then(()=>{
			uni.showToast({
				title:'选择成功'
			})
			setTimeout(()=>{
				uni.navigateBack();
			},2000)
			 
		})
		
	}

	const handleSelect = (date, id) => {
		if (getLasetSaturday()) return;
		data.selectList[date] = id;
	}

	// 获取已选择的套餐数量
	const getSelectedCount = () => {
		return Object.values(data.selectList).filter(id => id !== null).length;
	}

	// 检查是否全部选择
	const isAllSelected = () => {
		return data.comboList.every(combo => data.selectList[combo.date] !== null);
	}
</script>

<style lang="scss" scoped>
	.page-container {
		background: linear-gradient(180deg, #F8FAFB 0%, #FFFFFF 100%);
		min-height: 100vh;
		padding-bottom: 120rpx;
	}

	/* 页面标题 */
	.page-header {
		background: linear-gradient(135deg, #6FD719 0%, #5BC016 100%);
		padding: 60rpx 30rpx 40rpx;
		border-radius: 0 0 40rpx 40rpx;
		box-shadow: 0 4px 20px rgba(111, 215, 25, 0.2);
	}

	.header-content {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-bottom: 20rpx;
	}

	.header-icon {
		font-size: 48rpx;
		width: 80rpx;
		height: 80rpx;
		background: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.header-text {
		flex: 1;
	}

	.header-title {
		display: block;
		font-size: 36rpx;
		font-weight: 600;
		color: #FFFFFF;
		margin-bottom: 8rpx;
	}

	.header-subtitle {
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.8);
	}

	.weekend-notice {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 16rpx 20rpx;
		background: rgba(255, 152, 0, 0.1);
		border-radius: 20rpx;
		border: 1px solid rgba(255, 152, 0, 0.2);

		text {
			font-size: 24rpx;
			color: #FF9800;
			font-weight: 500;
		}
	}

	/* 学生信息卡片 */
	.student-info-container {
		padding: 20rpx 30rpx;
	}

	.student-info-card {
		background: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%);
		border-radius: 25rpx;
		padding: 30rpx;
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
		border: 1px solid rgba(255, 255, 255, 0.8);
		position: relative;
		overflow: hidden;
	}

	.student-info-card::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		width: 6rpx;
		height: 100%;
		background: linear-gradient(180deg, #6FD719 0%, #5BC016 100%);
	}

	.info-header {
		display: flex;
		align-items: center;
		gap: 12rpx;
		margin-bottom: 20rpx;
	}

	.info-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
	}

	.info-content {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.info-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 12rpx 16rpx;
		background: rgba(111, 215, 25, 0.03);
		border-radius: 12rpx;
		border: 1px solid rgba(111, 215, 25, 0.1);
	}

	.info-label {
		font-size: 26rpx;
		color: #666;
		font-weight: 500;
	}

	.info-value {
		font-size: 26rpx;
		color: #333;
		font-weight: 600;
	}

	/* 内容区域 */
	.content-container {
		padding: 30rpx;
	}

	.combo-day-section {
		margin-bottom: 30rpx;
		background: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%);
		border-radius: 25rpx;
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
		border: 1px solid rgba(255, 255, 255, 0.8);
		overflow: hidden;
	}

	.day-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		background: linear-gradient(135deg, #6FD719 0%, #5BC016 100%);
		color: #FFFFFF;
	}

	.day-info {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.day-date {
		font-size: 32rpx;
		font-weight: 600;
	}

	.day-week {
		font-size: 26rpx;
		opacity: 0.9;
		background: rgba(255, 255, 255, 0.2);
		padding: 6rpx 12rpx;
		border-radius: 12rpx;
	}

	.selection-status {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.status-text {
		font-size: 24rpx;
		color: #FFFFFF;
		font-weight: 500;
	}

	.combo-list {
		padding: 20rpx;
	}

	.combo-item-wrapper {
		display: flex;
		align-items: center;
		padding: 20rpx;
		margin-bottom: 16rpx;
		border-radius: 20rpx;
		border: 2rpx solid transparent;
		transition: all 0.3s ease;
		background: rgba(111, 215, 25, 0.02);

		&:last-child {
			margin-bottom: 0;
		}

		&:active {
			transform: scale(0.98);
		}

		&.combo-item-selected {
			border-color: #6FD719;
			background: rgba(111, 215, 25, 0.08);
			box-shadow: 0 4px 12px rgba(111, 215, 25, 0.2);
		}
	}

	.select-indicator {
		margin-left: 20rpx;
		flex-shrink: 0;
	}

	.select-btn {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #F5F7FA;
		border: 2rpx solid #E8EAED;
		transition: all 0.3s ease;

		&.select-btn-active {
			background: linear-gradient(135deg, #6FD719 0%, #5BC016 100%);
			border-color: #6FD719;
			box-shadow: 0 4px 12px rgba(111, 215, 25, 0.3);
		}
	}

	.select-text {
		font-size: 24rpx;
		color: #666;
		font-weight: 500;
	}

	/* 底部操作区域 */
	.bottom-action {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: linear-gradient(135deg, #FFFFFF 0%, #F8FAFB 100%);
		padding: 30rpx;
		border-top: 1px solid #F5F7FA;
		box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.08);
	}

	.action-info {
		margin-bottom: 20rpx;
		text-align: center;
	}

	.selected-count {
		font-size: 28rpx;
		color: #666;
		font-weight: 500;
	}

	/* 空状态 */
	.empty-container {
		background: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%);
		border-radius: 25rpx;
		padding: 80rpx 30rpx;
		text-align: center;
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
	}

	/* 动画效果 */
	.combo-day-section {
		animation: slideInUp 0.4s ease-out;
	}

	@keyframes slideInUp {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>